<template>
  <!-- 收货地址 -->
  <van-contact-card
    type="edit"
    :tel="address.tel"
    :name="`${address.name}—${address.region_text}`"
    @click="AddressChange"
    v-if="address"
  />
  <van-contact-card type="add" v-else @click="AddressAdd" />

  <!-- 订单列表 -->
  <van-card
    v-if="product"
    :thumb="product.thumbs_text"
    @click-thumb="toProductInfo(product.id)"
  >
    <!-- 卡片插槽部分 -->
    <template #title>
      <div class="title">{{ product.name }}</div>
    </template>

    <template #desc v-if="attribute.length > 0">
      <van-tag
        v-for="(value, key) in attribute"
        :key="key"
        class="tag"
        round
        plain
        type="primary"
        >{{ value.value + `${value.price > 0 ? `￥${value.price}` : ''}`}}
      </van-tag>
    </template>
    <template #desc v-else>
      <van-tag class="tag" round plain type="warning">无规格数据</van-tag>
    </template>
    <template #tags>
      <div>拼团价格：￥{{ product.team }}</div>
    </template>
  </van-card>

  <van-cell
    title="支付方式"
    :value="PayActive.text"
    is-link
    @click="PayShow = true"
  />
  
  <!--订单备注 -->
  <van-field
    v-model="remark"
    rows="5"
    autosize
    label="订单备注"
    type="textarea"
    maxlength="120"
    placeholder="请输入订单备注"
    show-word-limit
  />
  <!-- 提交动作栏 -->
  <van-submit-bar
    text-align="left"
    :price="total"
    button-text="确认支付"
    @submit="submit"
  />

  <!-- 支付方式弹出框 -->
  <van-popup v-model:show="PayShow" position="bottom">
    <van-picker
      title="支付方式"
      :columns="PayList"
      @confirm="Confirm"
      @cancel="PayShow = false"
    />
  </van-popup>

</template>
<script setup>
import { getCurrentInstance, onBeforeMount, ref } from "vue";


const { proxy } = getCurrentInstance();
// 获取商品id和选择的规格
let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0;
let relationids = proxy.$cookies.get('relationids') ? proxy.$cookies.get('relationids') : ''
let teamid = proxy.$cookies.get('teamid')

let product = ref({}); //购物车商品列表
let address = ref(null); //收货地址
let attribute = ref([])

//支付方式
let PayShow = ref(false);
let PayActive = ref({ text: "余额支付", value: "money" });
let PayList = ref([
  { text: "余额支付", value: "money" },
  { text: "微信支付", value: "wx" },
  { text: "支付宝", value: "afb" },
]);


//备注
const remark = ref();

onBeforeMount(() => {
  ProInfo();
  AddressInfo();
  AttrInfo();
});

//合计的价格
let total = computed(() => {
  var total = product.value.team ? product.value.team : 0;

  if(attribute.value.length > 0){
    attribute.value.map(item =>{total += parseFloat(item.price)})
  }

  return parseFloat(total * 100);
});


//商品信息
const ProInfo = async () => {
  // 组装数据
  var params = {
    busid: proxy.$business.value.id,
    proid,
  };

  var result = await proxy.$POST({
    url: "/product/info",
    params,
  });

  if (result.code == 0) {
    proxy.$fail(result.msg);
    return false;
  }

  product.value = result.data.product
  return false
};

//获取商品规格
const AttrInfo = async ()=>{
  var result = await proxy.$POST({
    url:'/product/attribute',
    params:{relationids}
  })

  if(result.code == 0){
    return false
  }

  attribute.value = result.data

}

//获取默认地址
const AddressInfo = async () => {
  // 先获取cookies中的地址
  var cached = proxy.$cookies.get("address")
    ? proxy.$cookies.get("address")
    : null;
  if (cached) {
    address.value = cached;
  } else {
    var result = await proxy.$POST({
      url: "/address/selected",
      params: { busid: proxy.$business.value.id },
    });

    if (result.code == 0) {
      return false;
    }
    address.value = result.data;
  }
};

//切换收货地址
const AddressChange = () => {
  proxy.$router.push({ path: "/address/index", query: { action: "selected" } });
};

//添加收货地址
const AddressAdd = () => {
  proxy.$router.push("/address/add");
};

//支付方式选择
const Confirm = ({ selectedOptions }) => {
  PayShow.value = false;
  //切换支付方式
  PayActive.value = selectedOptions[0];
};


//结算
const submit = async () => {
  var params = {
    busid: proxy.$business.value.id,
    pay: PayActive.value.value,
    relationids: relationids,
    addrid: address.value.id,
    remark: remark.value ? remark.value : "",
    teamid,
    proid
  };


  proxy
    .$confirm({
      message: "是否确认支付",
    })
    .then(async () => {
      var result = await proxy.$POST({
        url: "/teambus/add",
        params,
      });

      console.log(result)
      if (result.code == 0) {
        proxy.$fail(result.msg);
        return false;
      } else if (result.code == 1) {
        proxy.$success({
          message:result.msg,
          onClose:()=>{
            //清空拼团cookie的拼团id
            proxy.$cookies.set('teamid','')
            proxy.$cookies.set('relationids','')
            proxy.$router.push({path:'/team/info',query:{'teamid':teamid}})
          }
        });
        return false;
      }
    })
    .catch(() => {});
};
</script>